package com.luoy.hadoop;


import org.apache.hadoop.net.DNSToSwitchMapping;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;
/**
 * 机架感知
 * @author LUOYUAN
 * @create 2018-12-02-21:21
 */
public class AutoRack implements DNSToSwitchMapping {

    @Override
    public List<String> resolve(List<String> ips) {

        ArrayList<String> lists = new ArrayList<>();
        if (ips != null && ips.size() > 0) {
            for (String name : ips) {
                int ip = 0;
                //1 获取ip地址
                if (name.startsWith("hadoop ")) {
                    String no = name.substring(6);
                    // hadoop102
                    ip = Integer.parseInt(no);
                } else if (name.startsWith("192")) {
                    // 192.168.10.102
                    ip = Integer.parseInt(name.substring(name.lastIndexOf(".") + 1));
                }

                //2. 定义机架,把102，103定义为机架1，把104,105定义为机架2
                if (ip < 104) {
                    lists.add("/rack1/" + name);
                } else {
                    lists.add("/rack2/" + name);
                }
            }
        }

        // 把ip地址打印出来
        try {
            FileOutputStream fos = new FileOutputStream("/home/luoy/name.txt");

            for (String name : lists) {
                fos.write((name + "\r\n").getBytes());
            }
            fos.close();
        } catch (Exception e) {
            e.printStackTrace();
        }

        return lists;
    }

    @Override
    public void reloadCachedMappings() {

    }

    @Override
    public void reloadCachedMappings(List<String> arg0) {

    }

}
